package be.rhok.eenzaamheidswijzer.service;

import be.rhok.eenzaamheidswijzer.dao.QuestionDao;
import be.rhok.eenzaamheidswijzer.dao.SolutionDao;
import be.rhok.eenzaamheidswijzer.dao.UserLogDao;
import be.rhok.eenzaamheidswijzer.model.Question;
import be.rhok.eenzaamheidswijzer.model.Solution;
import be.rhok.eenzaamheidswijzer.model.UserLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class LonelyServiceImpl implements LonelyService {

    @Resource
    private QuestionDao questionDao;

    @Resource
    private SolutionDao solutionDao;

    @Resource
    private UserLogDao userLogDao;

    public Long createNewUser(String ip) {
        UserLog userLog = new UserLog();
        userLog.setStartDate(new Date());
        userLog.setIp(ip);
        userLogDao.persist(userLog);
        return userLog.getId();
    }

    public void logAnswer(Long token, Long answerId) {
        UserLog userLog = userLogDao.get(token);
        userLog.setLastModified(new Date());
        String answerSequence = StringUtils.trimToEmpty(userLog.getAnswerSequence());
        userLog.setAnswerSequence(answerSequence + answerId + ";");
        userLogDao.merge(userLog);
    }

    public void logSolution(Long token, Solution solution) {
        UserLog userLog = userLogDao.get(token);
        userLog.setLastModified(new Date());
        userLog.setSolution(solution);
        userLogDao.merge(userLog);
    }

    @Override
    public Question getQuestion(Long id) {
        return questionDao.get(id);
    }

    @Override
    public Solution getSolution(Long id) {
        return solutionDao.get(id);
    }
}